package com.seele.tigerwallet.ui.activtiy;

import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.seele.tigerwallet.R;
import com.seele.tigerwallet.model.TokenInfoModel;
import com.seele.tigerwallet.model.UserInfo;
import com.seele.tigerwallet.ui.MainActivity;
import com.seele.tigerwallet.ui.base.BaseActivity;
import com.seele.tigerwallet.ui.callback.OnLoginResponseListener;
import com.seele.tigerwallet.ui.manager.DaoManager;
import com.seele.tigerwallet.ui.manager.LoginManager;
import com.seele.tigerwallet.utils.EthWalletUtil;

import java.util.List;

import retrofit2.Call;

public class KeyActivity extends BaseActivity {

    private boolean mIsPwdAgain = false;
    private int currentIndex = -1; // 用于记录当前输入密码格位置
    private Button mBtnPwdNext;
    private TextView mTvPwdTitle;
    private String password = "";
    private TextView[] mTvPwd = new TextView[6];
    private TextView[] mBtnInput = new TextView[12];
    private LoginManager loginManager;

    protected static final String TAG = KeyActivity.class.getSimpleName();
    private List<String> mBundleStrings;


    @Override
    protected int getLayoutId() {
        return R.layout.wallet_password;
    }

    @Override
    protected void init() {
        initView();
    }

    private void initView() {
        try {
            if (null == loginManager) {
                loginManager = new LoginManager();
            }
            currentIndex = -1;
            mIsPwdAgain = false;
            Bundle bundle = getIntent().getExtras();
            if (null != bundle) {
                mBundleStrings = bundle.getStringArrayList(TAG);
            }
            View view = getLayoutInflater().inflate(R.layout.wallet_password, null);
            setContentView(view);
            mBtnPwdNext = (Button) findViewById(R.id.btn_pwd_next);
            mTvPwdTitle = (TextView) findViewById(R.id.tv_pwd_title);


            for (int i = 0; i < 6; i++) {
                int textViewId = getResources().getIdentifier("tv_pass" + i, "id", KeyActivity.this.getPackageName());
                mTvPwd[i] = (TextView) view.findViewById(textViewId);
            }

            for (int i = 0; i < 12; i++) {
                int textViewId = getResources().getIdentifier("btn_key" + i, "id", KeyActivity.this.getPackageName());
                mBtnInput[i] = (TextView) view.findViewById(textViewId);
            }
            LinearLayout deleteLayout = (LinearLayout) view.findViewById(R.id.layout_delete);
            deleteLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mBtnPwdNext.setEnabled(false);
                    if (currentIndex - 1 >= -1) { // 判断是否删除完毕————要小心数组越界
                        mTvPwd[currentIndex--].setText("");
                    }
                }
            });
        }catch (Exception e) {
            Log.e(TAG, "initView failed:" + e.getMessage());
        }
    }

    private void onPwdNext() {
        mIsPwdAgain = true;
        password = "";
        for (int i = 0; i < 6; i++) {
            password += mTvPwd[i].getText();
            mTvPwd[i].setText("");
        }
        this.mTvPwdTitle.setText(R.string.password_again);
        this.mBtnPwdNext.setText(R.string.ok);
        this.mBtnPwdNext.setEnabled(false);
        currentIndex = -1;

    }

    public void onBtnClick(View v) {
        try {
            if (v.getId() == R.id.btn_pwd_next) {
                if (mIsPwdAgain) {
                    onPwdOk();
                } else {
                    onPwdNext();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "onBtnClick failed:" + e.getMessage());
        }
    }

    private void onPwdOk() {
        String secondPassord = "";
        for (int i = 0; i < 6; i++) {
            secondPassord += mTvPwd[i].getText();
            mTvPwd[i].setText("");
        }
        if (TextUtils.isEmpty(secondPassord)) {
            Log.d(TAG, "意外错误`");
        }
        if (secondPassord.equals(password)) {
            createWallet(password);
        } else {
            showAlertDialog(R.string.inconsistent_password, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    initView();
                }
            });
        }
    }

    /**
     * 创建钱包
     *
     * @param password
     */
    private void createWallet(String password) {
        showLoadingDialog();
        new KeyAsyncTask(password, mBundleStrings).execute();
    }


    //创建钱包的异步线程
    class KeyAsyncTask extends AsyncTask<Void, Void, TokenInfoModel> {

        private String password;
        private List<String> mBundleStrings;

        public KeyAsyncTask(String pwd, List<String> bundleStrings) {
            this.password = pwd;
            this.mBundleStrings = bundleStrings;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected TokenInfoModel doInBackground(Void... voids) {
            TokenInfoModel tokenInfoModel = EthWalletUtil.createEthWallet(mBundleStrings, password);
            return tokenInfoModel;
        }


        @Override
        protected void onPostExecute(final TokenInfoModel tokenInfoModel) {
            try {
                if (tokenInfoModel == null) {
                    Toast.makeText(KeyActivity.this, R.string.create_wallet_error, Toast.LENGTH_LONG).show();
                    return;
                }

                UserInfo.get().address = tokenInfoModel.address;
                UserInfo.get().name = tokenInfoModel.name;
                loginManager.setOnResponseListener(new OnLoginResponseListener() {
                    @Override
                    public void onResponse(boolean isUpload) {
                        tokenInfoModel.isUpload = isUpload;
                        DaoManager.saveOrUpdate(tokenInfoModel);
                        Toast.makeText(KeyActivity.this, R.string.password_ok, Toast.LENGTH_SHORT).show();
                        //dismissLoadingDialog();
                        startActivity(MainActivity.class);
                        finish();

                    }

                    @Override
                    public void onFailureError(Call<String> call, Throwable t, int errorCode) {
                        DaoManager.saveOrUpdate(tokenInfoModel);
                        startActivity(MainActivity.class);
                        finish();
                    }
                });
                loginManager.create();
            }catch (Exception e) {
                Log.e(TAG, "onPostExecute failed:" + e.getMessage());
            }
        }
    }


    /**
     * 密码键盘点击事件
     *
     * @param view
     */
    public void onInputClick(View view) {
        try {
            String text = ((TextView) view).getText().toString();
            if (!TextUtils.isEmpty(text) && text.charAt(0) >= '0' && text.charAt(0) <= '9') { // 点击0~9按钮
                if (currentIndex >= -1 && currentIndex < 5) { // 判断输入位置————要小心数组越界
                    mTvPwd[++currentIndex].setText(text);
                }
                if (currentIndex == 5) {
                    mBtnPwdNext.setEnabled(true);
                }
            } else {
                if (view.getId() == R.id.btn_key11) { // 点击退格键
                    mBtnPwdNext.setEnabled(false);
                    if (currentIndex - 1 >= -1) { // 判断是否删除完毕————要小心数组越界
                        mTvPwd[currentIndex--].setText("");
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "onInputClick failed:" + e.getMessage());
        }

    }

    @Override
    protected void onDestroy() {
        if (null != loginManager) {
            loginManager = null;
        }
        super.onDestroy();
    }

}
